/*
 *             Copyright (C) 2024 Steve Jrong
 *
 * 	   GitHub Homepage: https://www.github.com/SteveJrong
 *      Gitee Homepage: https://gitee.com/stevejrong1024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stevejrong.waiter.common.component.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

/**
 * 工具类 - JSON
 *
 * @author Steve Jrong
 * @since 1.0
 */
@NoArgsConstructor
public final class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // JSON字符串转对象时，对象中缺少属性，仍允许转换成功
                .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) // 支持null值和空字符串
                .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // 允许单引号
    }

    /**
     * 对象转为JSON字符串
     *
     * @param sourceObject 待转换的对象
     * @return 转换后的JSON字符串
     */
    @SneakyThrows
    public static String objectToJsonString(Object sourceObject) {
        return OBJECT_MAPPER.writeValueAsString(sourceObject);
    }

    /**
     * JSON字符串转为对象
     *
     * @param sourceString 待转换的JSON字符串
     * @return 转换后的对象
     */
    @SneakyThrows
    public static <T> T jsonStringToObject(String sourceString, Class<T> classType) {
        return OBJECT_MAPPER.readValue(sourceString, classType);
    }
}